<?php
namespace app\shop\controller\admin;

use app\admin\library\AdminController;

class MemberLeveL extends AdminController{
    public function onIndex(){
        $this->pageTitle = '会员等级';
        $this->pageIcon = 'fa fa-diamond';
        return $this->display();
    }

    public function onList(){
        
        $type = $this->post('type',$this->check()->type('string'));

        $MemberLevel =  $this->model('MemberLevel');

        if ($type){
            $MemberLevel->where('type',$type);
        }

        $MemberLevel->order('sort','asc')->order('type','asc');

        return $MemberLevel->getData();
    }

    public function onSave(){

        $this->power('shop.setting.memberLevel');

        $level_id = $this->post('level_id',$this->check()->type('int'));

        $data['title'] = $this->post('title',$this->check()->type('string')->maxLength(40));
        $data['type'] = $this->post('type',$this->check()->type('string')->maxLength(40));
        $data['amount'] = $this->post('amount',$this->check()->type('int')->default(0));
        $data['brief'] = $this->post('brief',$this->check()->type('string'));

        $MemberLevel =  $this->model('MemberLevel');

        if ($level_id){
            $MemberLevel->updateId($level_id,$data);
            $this->log('修改会员等级',$data);
            return true;
        }else{
            $data['sort']= $MemberLevel->where('type',$data['type'])->max('sort')+1;
            $MemberLevel->insert($data);
            $this->log('添加会员等级',$data);
            return true;
        }

    }

    public function onDel(){
        $this->power('shop.setting.memberLevel');
        $level_id = $this->post('level_id',$this->check()->type('int')->required());
        
        $MemberLevel =  $this->model('MemberLevel');


        $oldData = $MemberLevel->getId($level_id);

        if (!$oldData){
            throw new \Exception('数据不存在');
        }


        if ($MemberLevel->deleteId($level_id)){
            $this->log('删除会员等级',$oldData);
            return true;
        }else{
            throw new \Exception('删除失败');
        }
    }

    public function onSort(){
        $this->power('shop.setting.memberLevel');
        $MemberLevel =  $this->model('MemberLevel');

        $ids = $this->post('ids',$this->check()->type('array')->required());

        if (count($ids)<2){
            throw new \Exception('排序失败');
        }

        $MemberLevel->switchSort($ids,'sort','asc');

        return true;
    }
}